﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using WaterRevenueMS.WebUI.Common;
using System.ComponentModel.Composition;
using WaterRevenueMS.Core.Service.Maintenance.Impl;
using WaterRevenueMS.WebUI.Extension.Filters;
using WaterRevenueMS.Domain.Common.Models;
using WaterRevenueMS.Domain.ViewModels.Maintenance.MeterTask;
using WaterRevenueMS.Core.Service.Maintenance;
using WaterRevenueMS.Componnent.Common;
using WaterRevenueMS.Componnent.Entities.Maintenance;
using WaterRevenueMS.WebUI.Extension.MvcHelper;
using WaterRevenueMS.Domain.ViewModels.BasicSet.WaterCaliber;
using WaterRevenueMS.Domain.ViewModels.BasicSet.Manufacturer;
using WaterRevenueMS.Core.Service.BasicSet;

namespace WaterRevenueMS.WebUI.Controllers
{

    [Export]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class MeterStQuerryController : AdminController
    {
        [Import]
        public IMeterTaskService MeterTaskService { get; set; }
        [Import]
        private IWaterCaliberService WaterCaliberService { get; set; }

        [Import]
        private IManufacturerService ManufacturerService { get; set; }


        [AdminLayoutAttribute]
        public ActionResult Index()
        {
            var modell = new MeterTaskModel();
            return View(modell);
        }
        [AdminPermission(PermissionCustomMode.Ignore)]
        public ActionResult List(DataTableParameter param)
        {
            int total = MeterTaskService.MeterTasks.Count(t => t.IsDeleted == false);

            var expr = BuildSearchCriteria();

            var filterResult = MeterTaskService.MeterTasks.Where(expr).Select(t => new MeterTaskModel
            {
                Id = t.Id,
                Bei_Z = t.Bei_Z,
                Cao_ZLX =  t.Cao_ZLX,
                New_SBDZ = t.New_SBDZ,
                Cao_ZYY = t.Cao_ZYY,
                Liu_SH = t.Liu_SH,
                Cao_ZY = t.Cao_ZY,
                UserName = t.MeterInfo.Customer != null ? t.MeterInfo.Customer.Hu_ZXM : "",
                Yi_BDZ = t.MeterInfo != null ? t.MeterInfo.Yi_BDZ : "",
                Shui_BCS_No = t.MeterInfo.Manufacturer != null ? t.MeterInfo.Manufacturer.Id : -1,
                Shui_BKJ_No = t.MeterInfo.WaterCaliber != null ? t.MeterInfo.WaterCaliber.Id : -1,
                

            }).OrderBy(t => t.Id).Skip(param.iDisplayStart).Take(param.iDisplayLength).ToList();

            int sortId = param.iDisplayStart + 1;

            var result = from c in filterResult
                         select new[]
                        {
                            sortId++.ToString(), 
                            c.Liu_SH,  
                            c.UserName,
                            c.CaoZLX,
                            c.Yi_BDZ,
                            c.Bei_Z,
                        c.Shui_BKJ_No.ToString(),
                        c.Shui_BCS_No.ToString(),
                            c.Id.ToString()
                        };

            return Json(new
            {
                sEcho = param.sEcho,
                iDisplayStart = param.iDisplayStart,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = result
            }, JsonRequestBehavior.AllowGet);
        }



        public ActionResult Create()
        {
            var model = new MeterTaskModel();
           
            return PartialView(model);
        }

        [HttpPost]
        [AdminOperateLog]
        public ActionResult Create(MeterTaskModel model)
        {
            if (ModelState.IsValid)
            {
                OperationResult result = MeterTaskService.Insert(model);
                if (result.ResultType == OperationResultType.Success)
                {
                    return Json(result);
                }
                else
                {
                    return PartialView(model);
                }
            }
            else
            {
                return PartialView(model);
            }
        }

        public ActionResult Edit(int Id)
        {
            var model = new MeterTaskModel();
            var entity = MeterTaskService.MeterTasks.FirstOrDefault(t => t.Id == Id);
            if (null != entity)
            {
                model = new MeterTaskModel
                {
                    Bei_Z =entity.Bei_Z,
                    Id = entity.Id
                    
                };

                model.Cao_ZLX = entity.Cao_ZLX;

                model.Meter_No = (int)entity.Meter_No;
               
            }
            return PartialView(model);
        }
       [HttpPost]
        public ActionResult Edit(MeterTaskModel model)
        {
            if (ModelState.IsValid)
            {
                if (model.Cao_ZLX == 4)
                {
                    if (!string.IsNullOrEmpty(model.New_SBDZ))
                    {
                        model.Cao_ZLX = 0;
                        MeterTaskService.ChangeYBDZ(model);
                    }
                    else
                    {
                        return PartialView(model);
                    }
                }
                else
                {

                }

                OperationResult result = MeterTaskService.Update(model);
                if (result.ResultType == OperationResultType.Success)
                {
                    return Json(result);
                }
                else
                {
                    return PartialView(model);
                }


            }
            else
            {
                return PartialView(model);
            }
        }

       public ActionResult ChangeSB(int Id)
       {
           var model = new MeterTaskModel();
           
           var entity = MeterTaskService.MeterTasks.FirstOrDefault(t => t.Id == Id);
           if (null != entity)
           {
               model = new MeterTaskModel
               {
                   Bei_Z = entity.Bei_Z,
                   Id = entity.Id

               };

               model.Cao_ZLX = entity.Cao_ZLX;
               if (entity.MeterInfo.WaterCaliber!=null)
               {
               model.Shui_BKJ_No = entity.MeterInfo.WaterCaliber.Id;
               }
               if (entity.MeterInfo.Manufacturer != null)
               {
                   model.Shui_BCS_No = entity.MeterInfo.Manufacturer.Id;
               }
               model.Meter_No = (int)entity.Meter_No;
               model.AN_ZWZ = entity.MeterInfo.An_ZWZ;
               model.Du_SBC = entity.MeterInfo.Du_SBC;
               model.Yi_BDZ = entity.MeterInfo.Yi_BDZ; 
              

           }
           InitModuleSet(model);
           return PartialView(model);
       }
       [HttpPost]
       public ActionResult ChangeSB(MeterTaskModel model)
       {
           if (ModelState.IsValid)
           {
               if ((model.Cao_ZLX == 4))
               {
                   if (!string.IsNullOrEmpty(model.New_SBDZ))
                   {
                     
                       MeterTaskService.ChangeYBDZ(model);
                   }
                   else
                   {
                       return PartialView(model);
                   }
               }
               else
               {

               }

               OperationResult result = MeterTaskService.Update(model);
               if (result.ResultType == OperationResultType.Success)
               {
                   return Json(result);
               }
               else
               {
                   return PartialView(model);
               }


           }
           else
           {
               return PartialView(model);
           }
       }

        private Expression<Func<MeterTask, Boolean>> BuildSearchCriteria()
        {
            DynamicLambda<MeterTask> bulider = new DynamicLambda<MeterTask>();
            Expression<Func<MeterTask, Boolean>> expr = null;
            if (!string.IsNullOrEmpty(Request["Liu_SH"]))
            {
                var data = Request["Liu_SH"].Trim();
                Expression<Func<MeterTask, Boolean>> tmp = t => t.Liu_SH.Contains(data);
                expr = bulider.BuildQueryAnd(expr, tmp);
            }

            if ((!string.IsNullOrEmpty(Request["Cao_ZLX"])) && (Request["Cao_ZLX"]!="-1"))
            {
                var data = Request["Cao_ZLX"].Trim();
                Expression<Func<MeterTask, Boolean>> tmp = t => t.Cao_ZLX.ToString().Contains(data);
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            if ((!string.IsNullOrEmpty(Request["Chu_LZT"])) && (Request["Cao_ZLX"] != "abcd"))
            {
                var data = Request["Chu_LZT"].Trim();
                Expression<Func<MeterTask, Boolean>> tmp = t => t.Chu_LZT.ToString().Contains(data);
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            Expression<Func<MeterTask, Boolean>> tmpSolid = t => t.Chu_LZT == false;
            expr = bulider.BuildQueryAnd(expr, tmpSolid);

            return expr;
        }
        private void InitModuleSet(MeterTaskModel model)
        {
            //水表口径
            var WatercaliberDatas = WaterCaliberService.WaterCalibers.Where(t => t.IsDeleted == false)
                .Select(t => new WaterCaliberModel
                {
                    Id = t.Id,
                    Shui_BKJ = t.Shui_BKJ
                });
            foreach (var item in WatercaliberDatas)
            {
                model.Shui_BKJItems.Add(new SelectListItem { Text = item.Shui_BKJ, Value = item.Id.ToString() });
            }
            //水表厂商
            var ManufacturerDatas = ManufacturerService.Manufacturers.Where(t => t.IsDeleted == false)
                .Select(t => new ManufacturerModel
                {
                    Id = t.Id,
                    Shui_BCS = t.Shui_BCS
                });
            foreach (var item in ManufacturerDatas)
            {
                model.Shui_BCSItems.Add(new SelectListItem { Text = item.Shui_BCS, Value = item.Id.ToString() });
            }
        }

    }

}
